package com.example.mail;

import com.example.entity.MailRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;

@Component
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    public void send(MailRequest mailRequest) {
        String from = mailRequest.getFrom();

        String subject = mailRequest.getSubject();
        String message = mailRequest.getMessage();
        boolean isHtml = mailRequest.isHtml();

        MimeMessagePreparator messagePreparator = mimeMessage -> {
            String[] to = null;
            if (mailRequest.getTo() != null) {
                to = mailRequest.getTo().toArray(new String[mailRequest.getTo().size()]);
            }
            String[] cc = null;
            if (mailRequest.getCc() != null) {
                cc = mailRequest.getCc().toArray(new String[mailRequest.getCc().size()]);
            }

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setCc(cc);
            messageHelper.setSubject(subject);
            messageHelper.setText(message, isHtml);
        };
        try {
            mailSender.send(messagePreparator);
        } catch (MailException e) {
            // runtime exception; compiler will not force you to handle it
            logger.error(e.getMessage(), e);
        }
    }
}
